import logging

from pylons import request, response, session
from pylons import tmpl_context as c
from pylons.controllers.util import abort, redirect_to, url_for

from formalchemyhandling.lib.base import BaseController
from formalchemyhandling.model import meta, Order, User

from formalchemy import FieldSet

log = logging.getLogger(__name__)

class FormController(BaseController):

    def index(self):
        """
        """
        return None

    def order(self):
        """
        """
        # query
        order_query = meta.Session.query(Order)
        order = order_query.first()

        # find a previous order
        if not order:
            # create user for test
            user = User()
            user.name = 'John'
            # save
            meta.Session.save_or_update(user)

            # create order for test
            order = Order()
            order.user = user
            order.quantity = 1
            # save
            meta.Session.save_or_update(order)

            # create user for test
            user = User()
            user.name = 'Bill'
            # save
            meta.Session.save_or_update(user)
            meta.Session.save_or_update(user)

            # create order for test
            order = Order()
            order.user = user
            order.quantity = 2
            # save
            meta.Session.save_or_update(order)

            # create user for test
            user = User()
            user.name = 'Test'
            # save
            meta.Session.save_or_update(user)

            # create order for test
            order = Order()
            order.user = user
            order.quantity = 3
            # save
            meta.Session.save_or_update(order)

            # update the session
            meta.Session.commit()

        # return the formalchemy content
        # return FieldSet(order).render()
        return FieldSet(order).quantity.render()

    def user(self):
        """
        """
        user_query = meta.Session.query(User)
        user = user_query.first()

        # find a previous order
        if not user:

            # create user for test
            user = User()
            user.name = 'Test'
            # save
            meta.Session.save_or_update(user)

        # return the formalchemy content
        # return FieldSet(user).render()
        return FieldSet(user).name.render()

